//
//  Utils.m
//  TwitterPlane
//
//  Created by kazuyuki takahashi on 10/02/06.
//  Copyright 2010 by invisibledesigner.com. All rights reserved.
//

#import "Utils.h"
#import "User.h"
#import "NSUserDefaults+App.h"


/**
 * 日時を 1 minute ago とかに変換
 */
static NSString *relativeDateStringFromNow(NSDate *date)
{
    NSTimeInterval ti = -[date timeIntervalSinceNow];
    
    const NSTimeInterval kOneDay = 60 * 60 * 24;
    NSInteger days = floor(ti / kOneDay);
    if (days >= 1) {
        NSString *unit = (days == 1) ? @"day" : @"days";
        return [NSString stringWithFormat:@"%d %@ ago", days, unit];
    }
    
    const NSTimeInterval kOneHour = 60 * 60;
    if (ti >= kOneHour) {
        NSInteger hours = floor(ti / kOneHour + 0.5);
        NSString *unit = (hours == 1) ? @"hour" : @"hours";
        return [NSString stringWithFormat:@"%d %@ ago", hours, unit];
    }
    
    const NSTimeInterval kOneMinute = 60;
    if (ti >= kOneMinute) {
        NSInteger minutes = floor(ti / kOneMinute + 0.5);
        NSString *unit = (minutes == 1) ? @"minute" : @"minutes";
        return [NSString stringWithFormat:@"%d %@ ago", minutes, unit];
    }
    
    return @"less than a minute ago";
}


NSString *dateStringForStatusView(NSDate *date)
{
    NSCParameterAssert(date != nil);
    
    DisplayDateOption option = [[NSUserDefaults standardUserDefaults] displayDateOption];
    
    switch (option) {
        case kDisplayDateOptionRelative:
            return relativeDateStringFromNow(date);
        case kDisplayDateOptionAbsolute:
        {
            NSDateFormatter *df = [[[NSDateFormatter alloc] init] autorelease];
            [df setDateStyle:NSDateFormatterShortStyle];
            [df setTimeStyle:NSDateFormatterShortStyle];
            return [df stringFromDate:date];
        }
        case kDisplayDateOptionDisabled:
            return nil;
        default:
            NSCAssert(NO, @"invalid option");
            return nil;
    }
}


NSString *usernameStringForStatusView(User *user)
{
    NSCParameterAssert(user != nil);
    
    DisplayNameOption option = [[NSUserDefaults standardUserDefaults] displayNameOption];
    
    switch (option) {
        case kDisplayNameOptionDisabled:
            return nil;
        case kDisplayNameOptionScreenName:
            return [user screenName];
        case kDisplayNameOptionFullName:
            return [user name];
        default:
            NSCAssert(NO, @"invalid option");
            return nil;
    }
}
